<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>列表排序</title></title>
        <script type="text/javascript" src="../js/vue.js"></script>
        
    </head>
    <body>
        <div id="root">
            <h2>遍历数组, key使用业务数据唯一标识</h2>
            <input type="text" placeholder="请输入关键字" v-model="pNameKey">
            <!-- <button @click="persons.sort((p1, p2) => p1.age - p2.age)">按年龄升序</button>
            <button @click="persons.sort((p1, p2) => p2.age - p1.age)">按年龄降序</button>
            <button @click="persons.sort((p1, p2) => p1.id - p2.id)">原顺序</button> -->
            <button @click="sortType=1">按年龄升序</button>
            <button @click="sortType=2">按年龄降序</button>
            <button @click="sortType=0">原顺序</button>
            <ul>
                <li v-for="p in personsCopy" :key="p.id">
                    {{p.name}} - {{p.age}} -- {{p.gender}}
                </li>
            </ul>

        </div>
    </body>
    <script>
        const vm = new Vue({
            el: "#root",
            data:{
                sortType :0,
                pNameKey:"",
                persons:[
                    {id:1, name: '马冬梅', age: 30,gender:"女"},
                    {id:2, name: '周冬雨', age: 19,gender:"女"},
                    {id:3, name: '周杰伦', age: 20,gender:"男"},
                    {id:4, name: '温兆伦', age: 21,gender:"男"},
                ]
            }, 
            computed:{
                personsCopy(){
                    const arr = this.persons.filter(p => p.name.indexOf(this.pNameKey) !== -1)
                    if(this.sortType === 1){
                        return arr.sort((p1, p2) => p1.age - p2.age)
                    }else if(this.sortType === 2){
                        return arr.sort((p1, p2) => p2.age - p1.age)
                    }
                    return arr
                }
            },
        })
    </script>
</html> 